package view.audit
{
	import base.components.PageBar;
	import base.components.PageChangeEvent;
	
	import business.UserDelegate;
	
	import com.adobe.utils.ArrayUtil;
	import com.adobe.utils.DateUtil;
	import com.adobe.utils.StringUtil;
	
	import events.MyLogEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.TitleWindow;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.DataGrid;
	import mx.controls.DateField;
	import mx.controls.Label;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.Application;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	
	public class ApplyUserMoneyClass extends TitleWindow
	{
		public var btnAdd:Button;
		public var btnSure:Button;
		public var btnDel:Button;
		public var btnQuery:Button;
		public var clr:Button;
		public var btnTxt:Button;
		public var datagrid:DataGrid;
		public var succeedColumn:DataGridColumn;
		public var startDate:DateField;
		public var endDate:DateField;
		public var userId:TextInput;
		public var pageBar:PageBar;
		public var txt:TextArea;
		public var resutlLabel:Label;
		
		[Bindable]
		public var infoArr:ArrayCollection;
		private var info:Object;
		
		private var delegateUser:UserDelegate;
		
		private var txtArr:Array;
		private var logId:String = '-1';	
		private var txtPan:TxtSureMoneyPanel;
		
		public function ApplyUserMoneyClass()
		{
			delegateUser = new UserDelegate(this);
		}
		
		public function init():void
		{
			infoArr = new ArrayCollection();
			btnAdd.addEventListener(MouseEvent.CLICK, onBtnAddClick);
			btnDel.addEventListener(MouseEvent.CLICK, onBtnDelClick);
			btnSure.addEventListener(MouseEvent.CLICK, onBtnSureClick);
			btnQuery.addEventListener(MouseEvent.CLICK, onBtnQueryClick);
			clr.addEventListener(MouseEvent.CLICK, onBtnClrClick);
			btnTxt.addEventListener(MouseEvent.CLICK, onBtnTxt);
		}
		
		private function onBtnTxt(event:MouseEvent):void
		{
			txtArr = [];
			var str:String = txt.text;
			var arr:Array = str.split("\r");
			var ids:Array = [];
			for(var i:int=0; i<arr.length; i++)
			{
				if(arr[i]=='')continue;
				var tempArr:Array = ArrayUtil.removeSpaceInArray(arr[i].split(" "));
				var obj:Object = {
					toUser:StringUtil.trim(tempArr[0]),
					nickname:'',
					orderTime:DateUtil.getFullDate(),
					chargeMoney:StringUtil.trim(tempArr[1]),
					info:tempArr[2]
				}
				txtArr.push(obj);
				ids.push(int(StringUtil.trim(tempArr[0])));
			}
			if(ids.length==0)return;
//			if(ArrayUtil.isRepeat(ids)==true)
//			{
//				txt.text = '';
//				Alert.show("文本中包含重复的宝宝ID，请重新输入没有重复的宝宝ID");
//				return;
//			}
			delegateUser.getUsersByIds(ids);
		}
		
		public function getUsersByIdsResult(result:Object, token:Object = null):void
		{
			result = result.result;
			var arr:Array = result.users; 
			if(arr.length==0)return;
			for(var i:int=0; i<arr.length; i++)
			{
				for(var j:int=0; j<txtArr.length; j++)
				{
					
					if(arr[i].bid==txtArr[j].toUser)
					{
						txtArr[j].nickname = arr[i].nickname ;
					}
				}
			}
			ArrayUtil.isRepeat(txtArr);
			if(txtPan)
			{
				this.removeChild(txtPan);
				txtPan = null;
			}
			txtPan = new TxtSureMoneyPanel();
			this.addChild(txtPan);
//			PopUpManager.addPopUp(txtPan, Application(Application.application));
//			PopUpManager.centerPopUp(txtPan);
//			txtPan.width = parentApplication.width;
//			txtPan.height = parentApplication.height;
			txtPan.grid.dataProvider = txtArr;
			
			addEventListener("TxtSureEvent", onTxtSureEvent);
			addEventListener("cancelTxtSureEvent", onCancelTxtSureEvent);
		}
		
		private function onCancelTxtSureEvent(event:Event):void
		{
			removeEventListener("cancelTxtSureEvent", onCancelTxtSureEvent);
			this.removeChild(txtPan);
			txtPan = null;
		}
		
		private function onTxtSureEvent(event:Event):void
		{
			removeEventListener("TxtSureEvent", onTxtSureEvent);
			txtPan.parent.removeChild(txtPan);
//			PopUpManager.removePopUp(txtPan);
			txtPan = null;
			resutlLabel.text = "充值成功！";
			txt.text = "";
			txtArr = [];
		}
		
		private function onBtnClrClick(event:MouseEvent):void
		{
			infoArr = new ArrayCollection();
			datagrid.dataProvider = infoArr;
			infoArr.refresh();
			succeedColumn.visible = false;
		}
		
		private function onBtnQueryClick(event:MouseEvent):void
		{
			// 查询
			delegateUser.getOrderHistory(DateUtil.parseDateToString(startDate.selectedDate), DateUtil.parseDateToString(endDate.selectedDate), userId.text, 1, 20);
		}
		
		public function getOrderHistoryResult(result:Object, token:Object = null):void
		{
			result = result.result;
			var obj:Object = {
				index:result.index,
				limit:result.limit,
				count:result.count
				
			};
			datagrid.dataProvider = result.data as Array;
			pageBar.setPageInfo(obj);
			pageBar.addEventListener(PageChangeEvent.NAME, onPageChange);
		}
		
		private function onPageChange(event:PageChangeEvent):void
		{
			delegateUser.getOrderHistory(DateUtil.parseDateToString(startDate.selectedDate), DateUtil.parseDateToString(endDate.selectedDate), userId.text, event.index, event.limit);
		}
		
		private function onBtnAddClick(event:MouseEvent):void
		{
			if(succeedColumn.visible==true)
			{
				Alert.show("请先清屏，再添加用户");
				return;
			}
//			if(infoArr.length>50)
//			{
//				Alert.show("最多为50个用户分配爱拍币！");
//				return;
//			}
			info = {
				toUser:'',
				nickname:'',
				orderTime:DateUtil.getFullDate(),
				chargeMoney:'',
				info:''
			};
			infoArr.addItemAt(info, infoArr.length);
		}
		
		private function onBtnSureClick(event:MouseEvent):void
		{
			var arr:Array = infoArr.source;
			for(var i:int=0; i<arr.length; i++)
			{
				if(arr[i].chargeMoney=='' || int(arr[i].chargeMoney)>10000){
					Alert.show(arr[i].toUser + "用户分配爱拍币不符合要求(大于0且小于10000)，请重新分配！");
					arr[i].chargeMoney = "";
					return;
				}
			}
			
			Alert.yesLabel = "确定";
			Alert.noLabel = "取消";
			Alert.show("确认要为这些用户充值吗？","提示",  Alert.YES | Alert.NO, null, onAddMoneysConfirmed, null, Alert.NO);
		}
		
		private function onAddMoneysConfirmed(event:CloseEvent):void
		{
			if (event.detail == Alert.YES)
			{
				LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goAddMoneys);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.USER, LogUtil.ADD, infoArr.source);
			}
		}
		
		private function goAddMoneys(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goAddMoneys);
			this.logId = event.logId;
			delegateUser.addMoneys(event.record);
		}
		
		private function onBtnDelClick(event:MouseEvent):void
		{
			if(datagrid.selectedItem!=null)
				infoArr.removeItemAt(infoArr.getItemIndex(datagrid.selectedItem));
		}
		
		public function getUsersById(id:int):void
		{
			delegateUser.getUsersById(id);
		}
		
		public function getUsersByIdResult(result:Object, token:Object = null):void
		{
			result = result.result;
			var obj:Object = result.users[0];
			if(obj==null)return;
			var arr:Array = infoArr.source; 
			for(var i:int=0; i<arr.length; i++)
			{
				if(arr[i].toUser==obj.bid)
				{
					arr[i].nickname = obj.nickname;
				}
			}
			infoArr.refresh();
		}
		
		public function addMoneysResult(result:Object, token:Object = null):void
		{
			result = result.result;
			var arr:Array = result as Array;
			var flag:Boolean = false;
			for(var i:int=0; i<arr.length; i++)
			{
				if(arr[i].code!=0){
					flag = true;
				}
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name,AppCons.USER,LogUtil.UPDATE,
					{bid:arr[i].toUser, AddMoeny:arr[i].chargeMoney, Reason:arr[i].info});
				
			}
			infoArr.source = arr;
			succeedColumn.visible = true;
			if(flag)
				Alert.show("充值出现错误!");
		}
		
		public function fault(error:FaultEvent, token:Object = null):void
		{
			Alert.show(error.fault.faultString, 'error');
		}
		
	}
}